package com.liuyjy.test.controller;

import com.liuyjy.base.redis.util.RedisCache;
import com.liuyjy.base.redis.util.RedissonLockUtil;
import com.liuyjy.test.domain.User;
import org.redisson.api.RLock;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Author liuyjy
 * @Date 2024/12/13 11:06
 * @Description: 验证架构包
 **/
@RestController
@RequestMapping("/redis")
public class RedisController {
    private static final String REDIS_KEY = "REDIS_KEY";
    @Resource
    private RedisCache redisCache;
    @Resource
    private RedissonLockUtil redissonLockUtil;

    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("5");
        Map<String, Set<String>> map = new HashMap<>();

        map.computeIfAbsent("1", k -> new HashSet<>()).add("3");
        System.out.println(map);
        map.computeIfPresent("1", (key, value) -> set);
        System.out.println(map);
    }

    @RequestMapping("/save")
    public User user() {
        String theonefx = "theonefx";
        User user = new User();
        user.setName(theonefx);
        user.setAge(666);
        redisCache.set(REDIS_KEY, theonefx, user, 300);
        return user;
    }

    @RequestMapping("/get")
    public User user(String name) {
        return redisCache.get(REDIS_KEY, name);
    }

    @RequestMapping("/lock")
    public User lock(String name) {
        RLock rLock = redissonLockUtil.getRLock(name);
        boolean tryLock = rLock.tryLock();
        if (!tryLock) {
            throw new RuntimeException("滚犊子！你老请求这个接口干什么！");
        }
        try {
            try {
                Thread.sleep(50000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            return user(name);
        } finally {
            rLock.unlock();
        }

    }


}
